<template>
  <q-page>
    <div class="container">
      <div class="text-center text-h4">Register</div>
      <q-card class="q-mt-md q-pa-md">
        <q-form @submit="submit">
          <q-input v-model="username"
                   label="Username"
                   dense
                   :rules="[
                   val => val.length >= 3 || 'The username is too short!',
                   val => val.length <= 16 || 'The username is too long!',
                   val => !/^[0-9]+$/.test(val) || 'The username cannot be pure number!',
                   val => !/^\w$/.test(val) || 'The username can only contains numbers, letters and underline!'
                 ]"/>
          <q-input v-model="password"
                   type="password"
                   label="Password"
                   dense
                   :rules="[
                   val => val.length >= 6 || 'The password is too short!',
                   val => val.length <= 20 || 'The password is too long!',
                   val => !/^([A-Z]|[a-z]|[0-9]|[`~!@#$%^&*()+=|{}':;',\[\]\\.<>/?])$/.test(val) ||
                    'The password can only contains numbers, letters and punctuations!'
                 ]"/>
          <q-input v-model="passwordConfirm"
                   type="password"
                   label="Confirm Password"
                   dense
                   :rules="[
                   val => val === password || 'The password is not same!'
                 ]"/>
          <q-input v-model="email"
                   label="Email"
                   dense
                   :rules="[
                   val => /[\w\.\-]+@([\w\-]+\.)+[\w\-]+/.test(val) || 'This is not a email address!'
                 ]"/>
          <q-btn class="full-width" color="primary" label="register" type="submit"/>
        </q-form>
      </q-card>
    </div>
  </q-page>
</template>

<script>
  import {Account} from 'src/lib/Account';

  export default {
    name: "Register",
    data: function () {
      return {
        username: '',
        password: '',
        passwordConfirm: '',
        email: ''
      };
    },
    methods: {
      async submit() {
        this.$q.loading.show();
        try {
          if (await Account.register(this.username, this.password, this.email)) {
            this.$q.notify({
              message: 'Success',
              caption: 'Register successfully!',
              icon: 'check'
            });
            await this.$router.push('/account/login');
          } else throw new Error('Register failed.')
        } catch {
        }
        this.$q.loading.hide();
      }
    }
  }
</script>

<style scoped>

</style>
